package org.demo;

import com.lmax.disruptor.RingBuffer;

import java.nio.ByteBuffer;

/**
 * @author yexi
 */
public class LongEventProducer {

    /**
     * RingBuffer: 环形队列
     * RingBuffer的序号，指向下一个可用的元素
     * 采用数组实现，没有首尾指针
     * 对比ConcurrentLinkedQueue，用数组实现的速度更快
     */
    private final RingBuffer<LongEvent> ringBuffer;

    public LongEventProducer(RingBuffer<LongEvent> ringBuffer) {
        this.ringBuffer = ringBuffer;
    }

    public void onData(ByteBuffer buffer) {
        long sequence = ringBuffer.next();
        try {
            LongEvent event = ringBuffer.get(sequence);
            event.setValue(buffer.getLong(0));
        } finally {
            ringBuffer.publish(sequence);
        }
    }

}
